package io.github.talelin.latticy.controller.v1;


import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.core.annotation.*;
import io.github.talelin.latticy.bo.BannerWithItemBO;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.impl.BannerServiceImpl;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;

@RequestMapping("/v1/banner")
@RestController()
@Validated
@PermissionModule("Banner")
public class BannerController {

    @Autowired
    private BannerServiceImpl bannerService;

    @PostMapping()
//    @LoginRequired
    @AdminRequired
    public CreatedVO create(@RequestBody @Validated BannerDTO bannerDTO ){
        BannerDO bannerDO = new BannerDO();
        BeanUtils.copyProperties(bannerDTO,  bannerDO);
        this.bannerService.save(bannerDO);
        return new CreatedVO();
    }


    @DeleteMapping("/{id}")
    @PermissionMeta(value = "删除Banner")
    @GroupRequired
    public DeletedVO delete(@PathVariable @Positive Long id){
        bannerService.deleteBanner(id);
        return new DeletedVO();
    }

    @GetMapping("/{id}")
    @LoginRequired
    @PermissionMeta(value = "查询Banner")
    @Logger(template = "{user.username}查询了Banner数据")
    public BannerWithItemBO getWithItems(@PathVariable @Positive() Long id){
        return bannerService.getWithItems(id);
    }

    @PutMapping("/{id}")
    @PermissionMeta(value = "更新Banner")
    @GroupRequired
    public UpdatedVO update(@PathVariable @Positive Long id, @RequestBody @Validated BannerDTO bannerDTO){
        BannerDTO bannerDTO1 = bannerDTO;
        bannerService.update(bannerDTO, id);
        return new UpdatedVO();
    }


    @GetMapping("/page")
    @LoginRequired
    public PageResponseVO<BannerDO> getBanners(@RequestParam(required = false, defaultValue = "0") @Min(value = 0) Integer page,
                                               @RequestParam(required = false, defaultValue = "10") @Min(value = 1) @Max(value = 20) Integer count) {

        Page<BannerDO> pager = new Page(page, count);
        IPage<BannerDO> paging = bannerService.getBaseMapper().selectPage(pager, null);
        return new PageResponseVO<BannerDO>(paging.getTotal(),paging.getRecords(),paging.getCurrent(),paging.getSize());
    }


}
